package cn.com.fssg.platform.base.handler.impl.gsl.common;

import cn.com.fssg.platform.base.handler.InterfaceHandler;
import cn.com.fssg.platform.biz.BizUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 工商联履职个人填报初始化表单接口
 */
@Component
public class GslFileSelectCtl implements InterfaceHandler {

    private NamedParameterJdbcTemplate jdbcTemplate = BizUtil.cur().tenantMainJdbcTemplate();

//    @Autowired
//    private NamedParameterJdbcTemplate jdbcTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object run(HttpServletRequest request, JSONObject jsonObject) throws Exception {
        String remarkId = jsonObject.getString("remarkId");
        String createBy = jsonObject.getString("createBy");
        String fileType = jsonObject.getString("fileType");
        if(StringUtils.isEmpty(createBy)) {
            createBy = BizUtil.cur().curUserId();
        }
        if(StringUtils.isEmpty(fileType)) {
            fileType = "image";
        }
        String querySql = "select * from wx_file where remark_id = :remarkId and create_by = :createBy and del_flag = '0' and type = :fileType";
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("remarkId", remarkId);
        queryParam.put("createBy", createBy);
        queryParam.put("fileType", fileType);
        List<Map<String, Object>> list = jdbcTemplate.queryForList(querySql, queryParam);
        if(!list.isEmpty()) {
            //获取图片以及文件信息
            List<Map<String, Object>> imgList = new ArrayList<>();
            String finalFileType = fileType;
            list.forEach(item -> {
                Map<String, Object> img = new HashMap<>();
                img.put("id", item.get("id"));
                img.put("file_name", item.get("display_name"));
                img.put("form_field", "image".equals(finalFileType) ? "file_imgs" : "file_Urls");
                img.put("form_code", "Form20251009104555");
                img.put("key_value", remarkId);
                img.put("file_path", item.get("path"));
                imgList.add(img);
            });
            return imgList;
        }
        return null;
    }
}
